'use strict';
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const glob = require('glob');


function isDebug() {
    return !(process.env.NODE_ENV === 'production');
}

let plugins = [
    new webpack.optimize.CommonsChunkPlugin(
        {
            name: 'common',   // 将公共模块提取
            minChunks: Infinity // 提取所有entry公用依赖的模块
        }),
    new webpack.ProvidePlugin({	//加载jq
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery'
    }),
    new ExtractTextPlugin('css/[name].css'),	//单独使用style标签加载css并设置其路径.[contenthash:6]
    new webpack.HotModuleReplacementPlugin(),
    new webpack.IgnorePlugin(/src\/lib\/*/)

];

if (!isDebug()) {
    const HappyPack = require('happypack');
    let happyThreadPool = HappyPack.ThreadPool({size: 5});
    plugins.push(new HappyPack({
        id: 'js',
        threadPool: happyThreadPool
    }));
}

function getEntry() {
    let entry = {};
    let files = glob.sync('./src/js/*.entry.js');
    for (let file of files) {
        let fileName = path.basename(file, '.entry.js');
        let tmpl = {
            favicon: './src/img/favicon.ico', // favicon路径
            filename: `./html/${fileName}.html`,
            template: `./src/html/${fileName}.html`,
            inject: true,
            chunks: ['common', fileName],  // 此处是载入提取的公共js，以及html同名js
            hash: true,
            minify: {	//压缩HTML文件
                removeComments: true,	// 移除HTML中的注释
                collapseWhitespace: false	// 删除空白符与换行符
            }
        };
        plugins.push(new HtmlWebpackPlugin(tmpl));
        entry[fileName] = [file];
    }
    return entry;
}


module.exports = {
    cache: true,
    devServer: {
        historyApiFallback: true,
        hot: true,
        inline: true,
        progress: true
    },
    entry: getEntry(),
    output: {
        path: path.join(__dirname, 'dist'),
        publicPath: 'http://localhost:4080/dist/',
        filename: 'js/[name].js',   // .[hash:6]
        chunkFilename: 'js/[name].js', // .[chunkhash:6]
    },
    module: {
        loaders: [	//加载器
            {test: /\.css$/, loader: ExtractTextPlugin.extract('style', 'css')},    //css加载器，只是这里改用了文件提取插件，将css提取出来单独作为一个文件进行存储。
            {test: /\.less$/, loader: ExtractTextPlugin.extract('css?sourceMap!' + 'less?sourceMap')},
            {
                test: /\.js$/,
                loader: 'babel?presets[]=es2015&cacheDirectory&sourceMap',
                include: [
                    // 只去解析运行目录下的 src 和 demo 文件夹
                    path.join(process.cwd(), './src'),
                ],
                happy: {id: 'js'}
            },
            {test: /\.html$/, loader: 'html'},
            {test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192&name=./img/[hash].[ext]'},
            {test: /\.(woff|woff2|eot|ttf|svg)$/, loader: 'url-loader?limit=8192&name=./fonts/[name].[ext]'}
        ]
    },
    plugins: plugins,
    resolve: {
        root: __dirname,
        extensions: ['', '.js', '.json', '.less'],
        alias: {
            bootstrap: 'src/lib/bootstrap/js/bootstrap.min.js',
            bootstrapCss: 'src/lib/bootstrap/css/bootstrap.min.css',
        }
    },
    externals: {
        '$': 'jquery'
    }
};

if (isDebug()) {
    module.exports.debug = true;
    module.exports.devtool = 'source-map';
} else {
    module.exports.plugins = (module.exports.plugins || []).concat([
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: JSON.stringify('production')
            }
        }),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            },
            except: ['$super', '$', 'exports', 'require']	//排除关键字
        }),
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.DedupePlugin()
    ]);
}